package com.dada.component;

import com.dada.config.SmsConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
@RequiredArgsConstructor
public class SmsComponent {
  private static final String URL_TEMPLATE = "https://jmsms.market.alicloudapi.com/sms/send"
      + "?mobile=%s&templateId=%s&value=%s";
  private final RestTemplate restTemplate;
  private final SmsConfig smsConfig;
  /**
   * 发送短信
   *
   * @param mobile 手机号
   * @param templateId 模板id
   * @param value  模板参数
   */
  public void sendSms(String mobile, String templateId, String value) {
    String url = String.format(URL_TEMPLATE, mobile, templateId, value);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set("Authorization","APPCODE "+smsConfig.appCode);
    HttpEntity httpEntity = new HttpEntity<>(httpHeaders);
    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity,
        String.class);
    if (response.getStatusCode().is2xxSuccessful()) {
      log.info("发送短信验证码成功");
    }else{
      log.error("发送短信验证码失败{}",response.getBody());
    }
  }

}
